package com.d.ui.view.progress;

import com.d.lib.ui.view.progress.SnapProgressBar;
import com.d.ui.view.ResourceTable;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import ohos.aafwk.ability.Ability;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.LayoutScatter;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

/**
 * Created by D on 2017/11/1.
 */
public class SnapProgressLayout extends DirectionalLayout implements Component.ClickedListener {
  private SnapProgressBar[] spbar_snaps;
  private Random mRandom = new Random();
  private EventHandler mHandler;
  private Task mTask;
  private boolean mIsRunning;
  private List<MediaInfo> mDatas = new ArrayList<>();
  private int mIndex;
  private int mCount;
  private Context mContext;

  public SnapProgressLayout(Context context) {
    super(context);
    init(context);
  }

  public SnapProgressLayout(Context context, AttrSet attrs) {
    super(context, attrs);
    init(context);
  }

  public SnapProgressLayout(Context context, AttrSet attrs, int defStyleAttr) {
    super(context, attrs, String.valueOf(defStyleAttr));
    init(context);
  }

  private void init(Context context) {
    mContext = context;
    Component view =
        LayoutScatter.getInstance(context).parse(ResourceTable.Layout_layout_progress_snap, this,
            true);
    bindView();
  }

  private void doTask() {
    if (mDatas.size() <= 0) {
      return;
    }
    float progress = 1f * mRandom.nextInt(100) / 100;
    progress = Math.max(0, progress);
    progress = Math.min(1, progress);
    progress = 0.33f * mCount + 0.33f * progress;

    MediaInfo media = mDatas.get(mIndex);
    spbar_snaps[4].setState(SnapProgressBar.STATE_PROGRESS).
        thumb(media.path)
        .progress(progress);

    if (++mCount > 2) {
      mCount = 0;
      mIndex++;
      if (mIndex >= mDatas.size()) {
        mIndex = 0;
      }
    }
  }

  private void restartTask() {
    stopTask();
    mHandler.postTask(mTask, 1000);
    mIsRunning = true;
  }

  private void stopTask() {
    mIsRunning = false;
    mHandler.removeTask(mTask);
  }

  private void bindView() {
    mHandler = new EventHandler(EventRunner.getMainEventRunner());
    mTask = new Task(this);
    spbar_snaps = new SnapProgressBar[]{
        (SnapProgressBar) findComponentById(ResourceTable.Id_spbar_snap_scanning),
        (SnapProgressBar) findComponentById(ResourceTable.Id_spbar_snap_padding),
        (SnapProgressBar) findComponentById(ResourceTable.Id_spbar_snap_done),
        (SnapProgressBar) findComponentById(ResourceTable.Id_spbar_snap_error),
        (SnapProgressBar) findComponentById(ResourceTable.Id_spbar_snap_progress)};
    spbar_snaps[0].setState(SnapProgressBar.STATE_SCANNING);
    spbar_snaps[1].setState(SnapProgressBar.STATE_PENDDING);
    spbar_snaps[2].setState(SnapProgressBar.STATE_DONE);
    spbar_snaps[3].setState(SnapProgressBar.STATE_ERROR);
    spbar_snaps[4].setState(SnapProgressBar.STATE_PROGRESS).progress(0);

    findComponentById(ResourceTable.Id_btn_start).setClickedListener(this::onClick);
  }

  private void requestPermission(final Runnable runnable) {
    if (runnable != null) {
      runnable.run();
    }
  }

  public void onDestroy() {
    stopTask();
  }

  @Override
  public void onClick(Component component) {
    requestPermission(new Runnable() {
      @Override
      public void run() {
        new Thread(new Runnable() {
          @Override
          public void run() {
            List<MediaInfo> list = Presenter.getPhotos(getContext().getApplicationContext());
            if (list.size() > 0) {
              mIndex = 0;
              mDatas.addAll(list);
              restartTask();
            }
          }
        }).start();
      }
    });
  }

  static class Task implements Runnable {
    WeakReference<SnapProgressLayout> weakRef;

    Task(SnapProgressLayout activity) {
      weakRef = new WeakReference<>(activity);
    }

    @Override
    public void run() {
      if (isFinished()) {
        return;
      }
      SnapProgressLayout ref = weakRef.get();
      ref.doTask();
      ref.mHandler.postTask(ref.mTask, 1000);
    }

    private boolean isFinished() {
      return weakRef == null || weakRef.get() == null
          || !weakRef.get().mIsRunning
          || weakRef.get().getContext() == null
          || weakRef.get().getContext() instanceof Ability
          && ((Ability) weakRef.get().getContext()).isTerminating();
    }
  }

  static class Presenter {
    //
    static List<MediaInfo> getPhotos(Context context) {
      List<MediaInfo> datas = new ArrayList<>();
      datas.add(new MediaInfo("1", ResourceTable.Media_lib_ui_layout_hl_ic_heart1));
      datas.add(new MediaInfo("2", ResourceTable.Media_lib_ui_layout_hl_ic_heart2));
      return datas;
    }
  }

  static class MediaInfo {
    public String id;
    public int path;

    public MediaInfo(String id, int path) {
      this.id = id;
      this.path = path;
    }

    @Override
    public String toString() {
      return "MediaInfo{" +
          "id='" + id + '\'' +
          ", path='" + path + '\'' +
          '}';
    }
  }
}
